package jobs.job3.classloaderdemo.user.algorithm;

import jobs.job3.classloaderdemo.server.standard.Task;
import jobs.job3.classloaderdemo.server.standard.serializer.IOSerializer;
import jobs.job3.classloaderdemo.server.standard.serializer.SerializerImp;

import java.io.Serializable;
import java.util.Arrays;

public class OrderMergeTask extends Task<OrderMergeTask.TwoArray, int[]> {

    @Override
    public int[] algorithm(TwoArray input) {
        return merge(input.getLeft(), input.getRight());
    }


    private int[] merge(int[] left, int[] right) {
        System.out.println("有序合并中...");
        System.out.println("合并前:" + Arrays.toString(left) +", "+ Arrays.toString(right));
        int[] array = new int[left.length + right.length];
        int li = 0;
        int ri = 0;
        int i = 0;
        while (li < left.length && ri < right.length) {
            int lv = left[li];
            int rv = right[ri];
            if (lv < rv) {
                array[i] = lv;
                li++;
            } else {
                array[i] = rv;
                ri++;
            }
            i++;
        }
        if (li < left.length)
            System.arraycopy(left, li, array, i, left.length - li);
        else
            System.arraycopy(right, ri, array, i, right.length - ri);
        System.out.println("合并后:" + Arrays.toString(array));
        return array;
    }

    public static class TwoArray implements Serializable {
        int[] left;
        int[] right;

        public TwoArray(int[] left, int[] right) {
            this.left = left;
            this.right = right;
        }

        public int[] getLeft() {
            return left;
        }

        public int[] getRight() {
            return right;
        }

        @Override
        public String toString() {
            return Arrays.toString(left) + "," + Arrays.toString(right);
        }
    }

    @Override
    public IOSerializer<TwoArray, int[]> getSerializer() {
        return new SerializerImp<>();
    }



}



